package com.dqm.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dqm.pojo.User;
import com.dqm.serviceImpl.UserServiceImpl;

@Controller
@RequestMapping
public class UserController {

	@Autowired
	private UserServiceImpl userServiceImpl;
	
	
	@RequestMapping("/signup")
	public String insertUser(HttpServletRequest request,Model model){
		String username = request.getParameter("username");
		String nickname = request.getParameter("nickname");
		String password = request.getParameter("password");
		
		User user = new User();
		user.setUsername(username);
		user.setNickname(nickname);
		user.setPassword(password);
		
		Boolean isExist = userServiceImpl.isExist(username);
		if(isExist == true) {
			model.addAttribute("isExist", "isExist");
			return "signup";
		}else {
			//model.addAttribute("user", user);
			userServiceImpl.insertUser(user);
			return "index";
		}
		
	}
	
	@RequestMapping("/login")
	public String loginUser(HttpServletRequest request,Model model){
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		
		Boolean isLogin = userServiceImpl.isLogin(user);
		if(isLogin){
			model.addAttribute("user", user);
			user = userServiceImpl.selectByUser(user);
			request.getSession().setAttribute("currentUser", user);
			return "user";
		}else {
			if(userServiceImpl.isEmpty(user)) {
				model.addAttribute("isLogin", "empty");
				return "index";
			}
			model.addAttribute("isLogin", "no");
			return "index";
		}
	}
	
	@RequestMapping("/reset")
	public String resetUser(HttpServletRequest request,Model model){
		User user = (User)request.getSession().getAttribute("currentUser");
		String username = user.getUsername();
		String password = request.getParameter("password");
		String nickname = request.getParameter("nickname");
		
		user.setUsername(username);
		user.setNickname(nickname);
		user.setPassword(password);
		userServiceImpl.updateByUsername(user);
		
		model.addAttribute("message", "reset");
		request.getSession().setAttribute("user", null);
		return "index";
	}
	
	@RequestMapping("/out")
	public String out(HttpServletRequest request,Model model) {
		request.getSession().setAttribute("user", null);
		return "index";
	}
	
}
